$(function() {	
	formatDateInput($("#txtBirthDate"));
	$('#patientForm').validate({
		onkeyup: false,
		onclick: false,
		onfocusout: function(element) {$(element).valid()}
	})
});

function formatDateInput(element){
	element.keyup(function(e){
        if (e.keyCode != 8){   
            if ($(this).val().length == 2){
                $(this).val($(this).val() + "/");
            } else if ($(this).val().length == 5){
                $(this).val($(this).val() + "/");
            }
        } else {
            var temp = $(this).val();
            
            if ($(this).val().length == 5){                
                $(this).val(temp.substring(0,4));    
            } else if (
            		$(this).val().length == 2){        
                $(this).val(temp.substring(0,1));    
            }
        }
    });
}

Date.prototype.formatDDMMYYYY = function(){
	var day = (this.getDate() < 10) ? ("0" + this.getDate()) : this.getDate();
	var month = (this.getMonth() < 10) ? ("0" + this.getMonth()) : this.getMonth();
	var year = this.getFullYear();
    return day + "/" + month + "/" + year;
}

dojoConfig = {async: true, parseOnLoad: false}
dojo.require("dojox.grid.DataGrid");
dojo.require('dojox.data.AndOrWriteStore');
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Button");

// here i have two variables for new or update patient cause i need to know
// if there is a valid patient to save when the user press Save.
var isNewPatient = false; // is a new patient (true)
var isUpdatepatient = false;// is an updated patient 

var grid;
var dataStore;
var patientsJson;

loadPatientsGrid();

function loadPatientsGrid()
{
	//Get all patients from database
	JManagerPatient.getAllPatients(fillGrid);    
}

function fillGrid(data)
{
	//create json which contains all the patients for the data grid.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
	patientsJson = new Array();
	for(var i=0;i<data.length;i++)
	{
		var patient = { 
					id:data[i].id, 
					first:data[i].name, 
					last:data[i].surname,
					address:data[i].address,
					birthDate:data[i].birthDate,
					idNumber:data[i].idNumber,
					telephone:data[i].telephone,
					notes:data[i].notes
				};
		patientsJson[i] = patient;
	}
	dojo.ready(init);
}

function init() 
{
	patientFormDisabled(true);
	var patientsData = {
            items: patientsJson,
            identifier: "id"      
        };
	
    dataStore = new dojox.data.AndOrWriteStore({data:patientsData});
    
    var layout = [[
		{ name: "id", field: "id", width: "8x", hidden:true},
		{ name: "Apellido", field: "last", width: "84px"},
		{ name: "Nombre", field: "first"},
		{ name: "Direccion", field: "address", hidden:true},
		{ name: "FechaNac", field: "birthDate", hidden:true},
		{ name: "DNI", field: "idNumber", hidden:true},
		{ name: "Telefono", field: "telephone", hidden:true},
		{ name: "Notas", field: "notes", hidden:true}
    ]];
    
    grid = new dojox.grid.DataGrid({
        id: 'grid',
        store: dataStore,
        structure: layout,
        rowSelector: true,
        autoHeight: 10,
        rowSelector: '0px',
        autoWidth: false,
        queryOptions: {ignoreCase: true},
        remove: function(id){
            delete this.index[id];
            for(var i = 0, l = this.data.length; i < l; i++){
                if(this.data[i][this.idProperty] == id){
                    this.data.splice(i, 1);
                    return;
                }
            }
        }
    });
    
    grid.placeAt("gridDiv");
    grid.startup(); 
    setupListeners();
}

function setupListeners(){
	dojo.connect(grid, "onSelectionChanged", grid, function(){
		var patientSelected = grid.selection.getSelected()[0];
		disableButton($("#btnEdit"),false);
		disableButton($("#btnSave"),true);
		disableButton($("#btnDelete"),false);	
		loadPatientData(patientSelected);	
	});
}

function loadPatientData(patient)
{
	if(patient != null)
	{
		// Load patient data into the form
		$("#txtName").val(patient.first);
		$("#txtSurname").val(patient.last);
		$("#txtIdNumber").val(patient.idNumber);
		$("#txtAddress").val(patient.address);
		$("#txtBirthDate").val(new Date(patient.birthDate).formatDDMMYYYY());
		$("#txtTelephone").val(patient.telephone);
		$("#txtNotes").val(patient.notes);
		patientFormDisabled(true);
	}
}

function filterGrid()
{
	var filter = "*"+$("#filterText").val()+"*";
	grid.filter({complexQuery: "last: '"+filter+"' OR 'first: '"+filter+"'"});
} 

var patientSelected;
function deleteSelectedPatient()
{
	if(grid.selection.getSelected().length)
	{
		patientSelected = grid.selection.getSelected()[0];
		var id = patientSelected.id;
		JManagerPatient.deletePatient(id[0],returnDeletePatient);
		clearPatientForm();
		patientFormDisabled(true);
		disableButton($("#btnEdit"),false);
		disableButton($("#btnSave"),false);
		disableButton($("#btnDelete"),true);	
	}	
}

function returnDeletePatient()
{
	var item = grid.selection.getSelected();
    var patientId = grid.store.getValue(item[0], "id");
    grid.store.deleteItem(item[0]); 
}

function addNewPatientToGrid(id)
{
	var p = getPatientFromForm();

	if(id != -1){
		dataStore.newItem({id : id, 
			first : p.name, 
			last: p.surname,
			address: p.address,
			birthDate: p.birthDate,
			idNumber: p.idNumber,
			telephone: p.telephone,
			notes: p.notes});
		disableButton($("#btnEdit"),false);
		disableButton($("#btnSave"),false);
		disableButton($("#btnDelete"),false);	
	}
}

function patientFormDisabled(disabled)
{
	$("#txtName").attr('disabled',disabled);
	$("#txtSurname").attr('disabled',disabled);
	$("#txtIdNumber").attr('disabled',disabled);
	$("#txtAddress").attr('disabled',disabled);
	$("#txtBirthDate").attr('disabled',disabled);
	$("#txtTelephone").attr('disabled',disabled);
	$("#txtNotes").attr('disabled',disabled);
	disableButton($("#btnSave"),disabled);
}

function clearPatientForm()
{
	$("#txtName").val('');
	$("#txtSurname").val('');
	$("#txtIdNumber").val('');
	$("#txtAddress").val('');
	$("#txtBirthDate").val('');
	$("#txtTelephone").val('');
	$("#txtNotes").val('');
}

function editPatient()
{
	if(grid.selection.getSelected().length)
	{
		isNewPatient = false;
		isUpdatepatient = true;
		patientFormDisabled(false);
		disableButton($("#btnEdit"),true);
		disableButton($("#btnSave"),false);
		disableButton($("#btnDelete"),false);		
	}
}

function newPatient()
{
	isNewPatient = true;
	isUpdatepatient = false;
	patientFormDisabled(false);
	clearPatientForm();
	disableButton($("#btnEdit"),true);
	disableButton($("#btnSave"),false);
	disableButton($("#btnDelete"),true);
}

function getPatientFromForm()
{
	var name = $("#txtName").val();
	var surname = $("#txtSurname").val();
	var idNumber = $("#txtIdNumber").val();
	var address = $("#txtAddress").val();
	
	var date = $("#txtBirthDate").val().split('/');
	var birthDate = new Date(date[2], date[1] - 1, date[0]);
	var telephone = $("#txtTelephone").val();
	var notes = $("#txtNotes").val();
	var p = {
			name: name,
			surname: surname,
			idNumber: idNumber,
			address: address,
			birthDate: birthDate,
			telephone: telephone,
			notes:notes
		};
	return p;
}

function savePatient()
{
	if($("#patientForm").validate()){
		if(isUpdatepatient || isNewPatient)
		{
			var p = getPatientFromForm();
			
			if(isNewPatient)
			{
				JManagerPatient.savePatient(p,addNewPatientToGrid);
			}
			else
			{
				patientSelected = grid.selection.getSelected()[0];
				var id = patientSelected.id;
				p["id"] = id[0];
				JManagerPatient.updatePatient(p,editPatientInGrid);
			}
			patientFormDisabled(true);
		}
	}	
}

function editPatientInGrid()
{
	var patientUpdated = getPatientFromForm();
	var selectedPatient = grid.selection.getSelected()[0];
	grid.store.setValue(selectedPatient, 'last', patientUpdated.surname);
	grid.store.setValue(selectedPatient, 'first', patientUpdated.name);
	grid.store.setValue(selectedPatient, 'address', patientUpdated.address);
	grid.store.setValue(selectedPatient, 'birthDate', new Date(patientUpdated.birthDate));
	grid.store.setValue(selectedPatient, 'idNumber', patientUpdated.idNumber);
	grid.store.setValue(selectedPatient, 'telephone', patientUpdated.telephone);
	grid.store.setValue(selectedPatient, 'notes', patientUpdated.notes);
}

function disableButton(button,disabled){
	if(disabled){
		button.removeClass("formButton");
		button.addClass("formButtonDisabled");
	}else{
		button.removeClass("formButtonDisabled");
		button.addClass("formButton");
	}
	button.attr('disabled',disabled);
}